package com.myqf.demo.反射.bz案例;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

public class Test2 {

	public static void main(String[] args) throws Exception {
		Class clz = Class.forName("ketang.Student");

		Student s1 = new Student();

		// 获取public的属性，包括继承
		Field[] fields = clz.getFields();

		for (Field field : fields) {
			System.out.println(field);

		}

		System.out.println("---------当前类中声明的所有属性-----------");
		// 当前类中声明的所有属性
		fields = clz.getDeclaredFields();
		for (Field field : fields) {
			System.out.println(field);
			System.out.println(field.getName());
			

		}
//
		// 父类中的所有属性
		
		System.out.println("-----------Field---------");
		Class personClz = clz.getSuperclass();
		fields = personClz.getDeclaredFields();
		for (Field field : fields) {
			System.out.println(field);
//			field.getName();

		}
		System.out.println("--------------------");
		//获取一个public的属性，包括继承，返回Field类型
		Field field = personClz.getField("age");
		field.set(s1, 1);
		System.out.println(s1.getAge());
//
		field = personClz.getDeclaredField("name");
		
		field.setAccessible(true);
		field.set(s1, "student1");

		System.out.println(s1.getName());
//
		System.out.println("--------------------构造");
//		Constructor constructor1 = clz.getConstructor();
//		System.out.println(constructor1);
		
		//通过构造方法获取对象
		Constructor constructor = clz.getDeclaredConstructor(String.class);
		constructor.setAccessible(true);
		Student s2 = (Student) constructor.newInstance("Student2");
		System.out.println(s2.getName());
	}

}
